// pages/data/grouplist/grouplist.js
import { apiClient, apiRoutes } from "../../../utils/api.js";
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    delete_mode: false,
    new_org_name:"",
    orgs:[],
    checkedValues: []
  },
  init_orgs_data(){
    apiClient.get(apiRoutes.orgs)
    .then(res =>{
      this.setData({
        orgs:res.data
      })
      app.globalData.orgs = res.data
    })
    .catch(err => {
      console.log(err)
      wx.showToast({
        title: "数据获取失败",
        icon:'error'
      })
      this.setData({
        orgs:[{id:0,name:"数据获取失败"+err.errMsg}]
      })
    })
  },
  new_org(){
    const name = this.data.new_org_name
    if(name){
      apiClient.post(
        apiRoutes.orgs,
        {name:name}
      ).then(res => {
        if(res.data){
          this.setData({
            'orgs': this.data.orgs.concat(res.data),
            new_org_name:""
          });
        }
      })
    }
  },
  checkboxChange(e) {
    // 获取勾选的checkbox的值
    const checkedValues = e.detail.value;
    this.setData({
      checkedValues: checkedValues
    });
  },
  trigger_delete(){
    this.setData({
      delete_mode:true
    })
  },
  delete(e){
    const tablename = "orgs"
    const id = e.currentTarget.dataset.id
    const url = apiRoutes.base+tablename+'/'+id+'/'
    console.log(url)
    wx.showModal({
      title: '删除确认',
      content: '确认删除吗？',
      complete: (res) => {
        if (res.confirm) {
          apiClient.delete(url).then(res => {
            // console.log(res)
            if(res.statusCode==204) {
              wx.showToast({
                title: '删除成功',
              })
              this.init_orgs_data()
            } else {
              wx.showToast({
                title: '删除失败',
                icon:'error'
              })
            }
          })
        } 
      }
    })
  },
  cancel_delete_mode(){
    this.setData({delete_mode:false})
  },
  navigateToOrg(e){
    app.globalData.orgid = e.currentTarget.dataset.id
    app.globalData.orgname = e.currentTarget.dataset.name
    if (app.globalData.orgid && app.globalData.orgname){
      wx.navigateTo({
        url: '/pages/data/group/group',
      })
    } else {
      console.log("获取失败")
    }
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init_orgs_data()
  },
})